package com.ruoyi.pad.controller;


import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.qrKey.CacheQrKeyUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pad.cache.CacheInterimDeviceUtils;
import com.ruoyi.pad.cache.CacheInterimPadUtils;
import com.ruoyi.pad.domain.KyDeviceInfo;
import com.ruoyi.pad.domain.KyPadInfo;
import com.ruoyi.pad.service.IKyDeviceInfoService;
import com.ruoyi.pad.service.IKyPadInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 仪器基础信息Controller
 */
@RestController
@RequestMapping("/data/device")
public class KyDeviceInfoController extends BaseController {
    @Resource
    private IKyDeviceInfoService kyDeviceInfoService;

    @Resource
    private IKyPadInfoService kyPadInfoService;

    @PreAuthorize("@ss.hasPermi('platform:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(KyDeviceInfo kyDeviceInfo) {
        startPage();
        kyDeviceInfo.setUserId(getUserId());
        kyDeviceInfo.setDeptId(getDeptId());
        List<KyDeviceInfo> list = kyDeviceInfoService.selectKyDeviceInfoList(kyDeviceInfo);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('platform:device:export')")
    @Log(title = "仪器基础信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(KyDeviceInfo kyDeviceInfo) {
        List<KyDeviceInfo> list = kyDeviceInfoService.selectKyDeviceInfoList(kyDeviceInfo);
        ExcelUtil<KyDeviceInfo> util = new ExcelUtil<>(KyDeviceInfo.class);
        util.exportExcel(list, "仪器基础信息数据");
    }


    @PreAuthorize("@ss.hasPermi('platform:device:query')")
    @GetMapping(value = "/{devId}")
    public AjaxResult getInfo(@PathVariable("devId") Long devId) {
        return success(kyDeviceInfoService.selectKyDeviceInfoByDevId(devId));
    }


    @PreAuthorize("@ss.hasPermi('platform:device:add')")
    @Log(title = "仪器基础信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KyDeviceInfo kyDeviceInfo) {
        return toAjax(kyDeviceInfoService.insertKyDeviceInfo(kyDeviceInfo));
    }


    @PreAuthorize("@ss.hasPermi('platform:device:edit')")
    @Log(title = "仪器基础信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KyDeviceInfo kyDeviceInfo) {
        return toAjax(kyDeviceInfoService.updateKyDeviceInfo(kyDeviceInfo));
    }


    @PreAuthorize("@ss.hasPermi('platform:device:remove')")
    @Log(title = "仪器基础信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{devIds}")
    public AjaxResult remove(@PathVariable Long[] devIds) {
        if (devIds != null && devIds.length != 0) {
            for (int i = 0; i < devIds.length; i++) {
                Long devId = devIds[i];
                KyDeviceInfo deviceInfo = kyDeviceInfoService.selectKyDeviceInfoByDevId(devId);
                List<KyPadInfo> kyPadInfoEntityList = kyPadInfoService.selectKyPadInfoByDevNum(deviceInfo.getDevNum());
                if (kyPadInfoEntityList != null && kyPadInfoEntityList.size() != 0) {
                    List<Long> padIds = kyPadInfoEntityList.stream().map(KyPadInfo::getPadId).collect(Collectors.toList());
                    kyPadInfoService.deleteKyPadInfoByPadIds(padIds.toArray(new Long[padIds.size()]));
                }
            }
        }
        return toAjax(kyDeviceInfoService.deleteKyDeviceInfoByDevIds(devIds));
    }


    //@PreAuthorize("@ss.hasPermi('platform:device:add')")
    @GetMapping(value = "/qr-key/generate")
    public AjaxResult generateQrKey() {
        String uuid = IdUtils.fastSimpleUUID();
        CacheQrKeyUtils.setQrCache(uuid, getLoginUser());
        return AjaxResult.success(uuid);
    }

    /**
     * 销毁仪器注册二维码-key
     * @param key
     * @return
     */
    @PreAuthorize("@ss.hasPermi('platform:device:add')")
    @GetMapping(value = "/qr-key/destroy/{key}")
    public AjaxResult destroyQrKey(@PathVariable String key) {
        return toAjax(CacheQrKeyUtils.removeQrCache(key));
    }

    /**
     * 查询扫码的设备
     * @param bindKey
     * @return
     */
    @PreAuthorize("@ss.hasPermi('platform:device:add')")
    @GetMapping(value = "/bind/interim/list/{bindKey}")
    public AjaxResult listInterimInfo(@PathVariable String bindKey) {
        List<KyDeviceInfo> deviceInfoList = new ArrayList<>();
        // 读取Redis中缓存的Pad信息
        List<KyPadInfo> padCacheList = CacheInterimPadUtils.getPadListCache(bindKey);

        Map<String, List<KyPadInfo>> padMap = padCacheList.stream().collect(Collectors.groupingBy(KyPadInfo::getDevNum));
        for (Map.Entry<String, List<KyPadInfo>> entry : padMap.entrySet()) {
            String devNum = entry.getKey();
            List<KyPadInfo> kyPadInfoEntityList = entry.getValue();
            KyDeviceInfo devInfo = CacheInterimDeviceUtils.getDeviceCache(bindKey + "," + devNum);
            if (devInfo == null) {
                devInfo = kyDeviceInfoService.selectKyDeviceInfoByDevNum(devNum);
            }
            if (devInfo != null) {
                String allSN = kyPadInfoEntityList.get(0).getPadSn();
                for (int i = 1; i < kyPadInfoEntityList.size(); i++) {
                    allSN += "&&" + kyPadInfoEntityList.get(i).getPadSn();
                }
                devInfo.setAllSN(allSN);
                deviceInfoList.add(devInfo);
            }
        }
        return AjaxResult.success(deviceInfoList);
    }

    /**
     * 保存扫码绑定的设备
     * @param bindKey
     * @return
     */
    @Log(title = "保存临时设备数据", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('platform:device:add')")
    @GetMapping(value = "/bind/interim/save/{bindKey}")
    public AjaxResult saveInterimInfo(@PathVariable String bindKey) {

        List<KyDeviceInfo> deviceList = new ArrayList<>();
        List<KyPadInfo> padList = new ArrayList<>();

        // 读取Redis中缓存的Pad信息
        List<KyPadInfo> padCacheList = CacheInterimPadUtils.getPadListCache(bindKey);

        for (int i = 0; i < padCacheList.size(); i++) {
            KyPadInfo padInfo = padCacheList.get(i);
            padInfo.setUserId(getUserId());
            padInfo.setDeptId(getDeptId());
            padInfo.setCreateTime(new Date());

            KyDeviceInfo devInfo = CacheInterimDeviceUtils.getDeviceCache(bindKey + "," + padInfo.getDevNum());
            if (devInfo == null) {
                devInfo = kyDeviceInfoService.selectKyDeviceInfoByDevNum(padInfo.getDevNum());
            }

            if (devInfo != null) {
                devInfo.setUserId(getUserId());
                devInfo.setDeptId(getDeptId());
                devInfo.setCreateTime(new Date());
                deviceList.add(devInfo);
                padList.add(padInfo);
            }
        }

        // 批量插入 ”设备信息“、”平板信息“
        int insertDevNum = kyDeviceInfoService.batchInsert(deviceList);
        int insertPadNum = kyPadInfoService.batchInsert(padList);
        return AjaxResult.success("插入" + insertDevNum + "条设备信息，" + insertPadNum + "条平板信息");
    }

    /**
     * 删除扫码的设备
     * @param bindKey
     * @return
     */
    @PreAuthorize("@ss.hasPermi('platform:device:add')")
    @GetMapping(value = "/bind/interim/clear/{bindKey}")
    public AjaxResult clearInterimInfo(@PathVariable String bindKey) {
        boolean isOkDev = CacheInterimDeviceUtils.removeDeviceCache(bindKey);
        boolean isOkPad = CacheInterimPadUtils.clearPadCache(bindKey);
        return AjaxResult.success();
    }

    /**
     * 查询新绑定的设备
     * @param startTime
     * @return
     */
    @PreAuthorize("@ss.hasPermi('platform:device:add')")
    @GetMapping(value = "/bind/new/list/{startTime}")
    public AjaxResult listNewBindList(@PathVariable Long startTime) {

        LoginUser loginUser = getLoginUser();
        List<KyDeviceInfo> deviceInfoList = kyDeviceInfoService.selectNewKyDeviceInfoList(loginUser.getDeptId(), startTime);
        if (deviceInfoList != null && deviceInfoList.size() != 0) {
            deviceInfoList.forEach(item ->{
                // 查询此设备的平板信息
                List<KyPadInfo> kyPadInfoEntities = kyPadInfoService.selectKyPadInfoByDevNum(item.getDevNum());
                if (kyPadInfoEntities != null && kyPadInfoEntities.size() != 0) {
                    String allSN = kyPadInfoEntities.get(0).getPadSn();
                    for (int i = 1; i < kyPadInfoEntities.size(); i++) {
                        allSN += ( "&&" + kyPadInfoEntities.get(i).getPadSn());
                    }
                    item.setAllSN(allSN);
                }
            });
        }
        return AjaxResult.success(deviceInfoList);
    }

}
